package com.algernoon.nettydemo.bio.server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Date;

public class TimeServerHandler implements Runnable {

	private Socket socket;

	public TimeServerHandler(Socket socket) {
		this.socket = socket;
	}

	@Override
	public void run() {

		BufferedReader in = null;
		PrintWriter out = null;
		try {
			in = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
			out = new PrintWriter(this.socket.getOutputStream(), Boolean.TRUE);

			String currentTime = null;
			String body = null;
			// 读取请求并根据逻辑作出响应
			while (true) {
				body = in.readLine();
				if (body == null)
					break;
				System.out.println("The time server receive order: " + body);
				currentTime = "QUERY_TIME_ORDER".equalsIgnoreCase(body)
						? new Date(System.currentTimeMillis()).toString() : "BAD ORDER PARAMETER";
				// 响应内容给客户端
				out.println(currentTime);
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			// 释放输入流、输出流、Socket套接字句柄资源
			if (in != null) {
				try {
					in.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
			if (out != null) {
				out.close();
				// 释放out供下次请求使用
				out = null;
			}
			if (this.socket != null) {
				try {
					socket.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
				// 释放socket供下次请求使用
				this.socket = null;
			}
		}

	}

}
